package com.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.results.format.ResultFormatType;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;

/**
 * @ClassName LongAdderTest
 * @Description TODO
 * @Author: XMK
 * @Date: 2021/4/14 11:48
 * @Version: 1.0
 */
@BenchmarkMode(Mode.AverageTime)
@Warmup(iterations = 1, time = 1)
@Measurement(iterations = 5, time = 5)
@Threads(10)
@Fork(1)
@State(value = Scope.Benchmark)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class LongAdderUseJMH {

    private final int N_TIME = 100_000_000;

    public static void main(String[] args) throws RunnerException {

        Options opt = new OptionsBuilder()
                .include(LongAdderUseJMH.class.getSimpleName())
                .result("result.json")
                .resultFormat(ResultFormatType.JSON).build();
        new Runner(opt).run();
    }


    @Benchmark
    public void testLongAdder(Blackhole blackhole) {

        LongAdder adder = new LongAdder();

        for (int j = 0; j < N_TIME; j++) {
            adder.increment();
        }

        blackhole.consume(adder.longValue());
    }

    @Benchmark
    public void testAtomicLong(Blackhole blackhole) {

        AtomicLong adder = new AtomicLong();
        for (int j = 0; j < N_TIME; j++) {
            adder.incrementAndGet();
        }

        blackhole.consume(adder.longValue());
    }
}
